package com.matuw.android.util;

import android.os.SystemClock;
import android.view.View;

import androidx.annotation.NonNull;

/**
 * @author Shihwan
 * @date 2025/6/13
 */
public class ViewUtils {
    /**
     * 点击防抖的默认时间
     */
    private static long debounceClickInterval = 400;

    public static long getDebounceClickInterval() {
        return debounceClickInterval;
    }

    public static void setDebounceClickInterval(long debounceClickInterval) {
        ViewUtils.debounceClickInterval = debounceClickInterval;
    }

    public static void debounceClick(@NonNull View view, long interval, View.OnClickListener listener) {
        view.setOnClickListener(new DebounceClickListener(interval, listener));
    }

    public static void debounceClick(@NonNull View view, View.OnClickListener listener) {
        debounceClick(view, debounceClickInterval, listener);
    }

    /**
     * 防重复点击
     */
    public static class DebounceClickListener implements View.OnClickListener {

        private final long interval;
        private final View.OnClickListener listener;
        private long lastClickTime;

        public DebounceClickListener(long interval, View.OnClickListener listener) {
            this.interval = interval;
            this.listener = listener;
        }

        @Override
        public void onClick(View v) {
            long time = SystemClock.elapsedRealtime();
            if (time - lastClickTime < interval) return;
            lastClickTime = time;
            if (listener != null) {
                listener.onClick(v);
            }
        }
    }
}
